// scaup - Scala up!
// (c) 2008-2010, Normen Müller, normen.mueller@gmail.com  
// $Id: net.scala 80 2010-05-13 12:31:58Z normen.mueller $
package scaup.data

import java.net._
import java.io._

import scaup.Views._

/** Adds extra methods to <code>java.net.URI</code>.
 * 
 *  @author <a href="mailto:normen.mueller@googlemail.com">Normen M&#xFC;ller</a>
 *  @version 0.0.5
 * 
 *  @note: Due to the worst equals/hasCode implementation of java.net.URL, there won't be any URLExtras.
 *    Use URI/ URIExtras instead (cf. http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html).
 * 
 *  @param uri to enclose/ extend
 */
private [scaup] class URIExtras(uri: URI) extends PartiallyOrdered[URI] {
  if (uri == null)
    error("URI may not be null")

  lazy val toList = uri.toString.split('/').foldLeft(Nil: List[String])((l,d) => l::: List(d))
  
  lazy val utf8enc = URLEncoder.encode(uri.toString(), "UTF-8")
  
  lazy val utf8dec = URLDecoder.decode(uri.toString(), "UTF-8")
  
  def /(child: String) = new URI(uri.getScheme, uri.getUserInfo, uri.getHost, uri.getPort, {
    if(uri.getPath endsWith "/")
      if(child startsWith "/") uri.getPath + child substring 1
      else uri.getPath + child
    else
      if(child startsWith "/") uri.getPath + child
      else uri.getPath + "/" + child
  }, uri.getQuery, uri.getFragment)
  
  def --(that: URI) = (uri.toList --- that.toList) mkString "/"
  
  def tryCompareTo[B >: URI <% PartiallyOrdered[B]](that: B): Option[Int] = that match {
    case x: URI =>
      if(uri.toList == x.toList)
        Some(0)
      else if(uri.toList startsWith x.toList)
        Some(-1)
      else if(x.toList startsWith uri.toList)
        Some(1)
      else None
    case _ => None
  }      
}
